package com.tbit.uqbike.client.controller;

import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.Result;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.pojo.dto.UnpaidOrderUseCarDTO;
import com.tbit.uqbike.client.pojo.vo.UnpaidOrderCanUseCarVO;
import com.tbit.uqbike.client.pojo.vo.UnpaidOrderUseCarFee;
import com.tbit.uqbike.client.service.TokenService;
import com.tbit.uqbike.client.service.UnpaidOrderDeductionService;
import com.tbit.uqbike.client.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;

/**
 * 未支付订单卡券抵扣相关功能
 *
 * @author <a href="mailto:chen.wutian@tbit.com.cn">BUGTian</a>
 * @since 2025/5/15
 */
@RestController
@RequestMapping("/unpaidOrder")
public class UnpaidOrderDeductionController {


    @Autowired
    private UnpaidOrderDeductionService unpaidOrderDeductionService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserServiceImpl userService;

    /**
     * 获取未支付订单可使用卡券
     * @return 可使用卡券信息
     */
    @GetMapping("/getUnpaidOrderCanUseCar")
    public Result<UnpaidOrderCanUseCarVO> getUnpaidOrderCanUseCar(String orderNO) {
        return Result.success(unpaidOrderDeductionService.getUnpaidOrderCanUseCar(orderNO));
    }


    /**
     * 根据卡券获取抵扣后的费用详情
     * @param orderNO 订单编号
     * @param unpaidOrderUseCarDTO 使用的卡券信息
     * @return 未支付订单使用卡券抵扣后的费用详情
     */
    @GetMapping("/getFee")
    public Result<UnpaidOrderUseCarFee> getFee(@NotNull(message = "订单编号不能为空") String orderNO, UnpaidOrderUseCarDTO unpaidOrderUseCarDTO) {
        UnpaidOrderUseCarFee unpaidOrderUseCarFee = unpaidOrderDeductionService.getFee(orderNO, unpaidOrderUseCarDTO);
        User user = userService.getByUserId(unpaidOrderUseCarFee.getRideLogDetails().getUserId());
        unpaidOrderUseCarFee.computeWaitingPayMoney(user.getMoney().longValue());
        return Result.success(unpaidOrderUseCarFee);
    }

    /**
     * 使用卡券进行抵扣
     * @param orderNO 订单编号
     * @param unpaidOrderUseCarDTO 使用的卡券信息
     * @return 成功/失败
     */
    @PostMapping("/useCar")
    public Result<Boolean> useCar(@NotNull(message = "订单编号不能为空") String orderNO, UnpaidOrderUseCarDTO unpaidOrderUseCarDTO, String token) {
        if (unpaidOrderUseCarDTO.getCouponuserId() == null && unpaidOrderUseCarDTO.getRideCardId() == null && unpaidOrderUseCarDTO.getVipId() == null) {
            //未使用卡券的情况
            return Result.success(true);
        }
        User user = tokenService.getUser(token);
        if (user == null) {
            throw new BaseException("user_not_exist");
        }
        return Result.success(unpaidOrderDeductionService.useCar(orderNO, unpaidOrderUseCarDTO, user));
    }


}
